using Microsoft.AspNetCore.Mvc;
using ProduceBasicData.Api.DTO;
using ProduceBasicData.Api.Services;
using ProduceBasicData.ErrorCode;
using System.ComponentModel.DataAnnotations;

namespace ProduceBasicData.Api.Controllers
{
    /// <summary>
    /// 通知管理控制器
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    public class NotificationController : ControllerBase
    {
        private readonly INotificationService _notificationService;
        private readonly ILogger<NotificationController> _logger;

        public NotificationController(INotificationService notificationService, ILogger<NotificationController> logger)
        {
            _notificationService = notificationService;
            _logger = logger;
        }

        /// <summary>
        /// 获取用户通知列表
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <param name="pageIndex">页码（默认1）</param>
        /// <param name="pageSize">页大小（默认10）</param>
        /// <param name="isRead">是否已读（可选）</param>
        /// <returns></returns>
        [HttpGet("list")]
        public async Task<ApiResult<ApiPaging<NotificationDto>>> GetUserNotifications(
            [FromQuery] int userId,
            [FromQuery] int pageIndex = 1,
            [FromQuery] int pageSize = 10,
            [FromQuery] bool? isRead = null)
        {
            try
            {
                if (userId <= 0)
                {
                    return new ApiResult<ApiPaging<NotificationDto>>
                    {
                        Code = ApiEnum.Failed,
                        Msg = "用户ID无效"
                    };
                }

                var result = await _notificationService.GetUserNotificationsAsync(userId, pageIndex, pageSize, isRead);
                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取用户通知列表失败，用户ID: {UserId}", userId);
                return new ApiResult<ApiPaging<NotificationDto>>
                {
                    Code = ApiEnum.Failed,
                    Msg = $"获取通知列表失败: {ex.Message}"
                };
            }
        }

        /// <summary>
        /// 获取未读通知数量
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <returns></returns>
        [HttpGet("unread-count")]
        public async Task<ApiResult<int>> GetUnreadCount([FromQuery] int userId)
        {
            try
            {
                if (userId <= 0)
                {
                    return new ApiResult<int>
                    {
                        Code = ApiEnum.Failed,
                        Msg = "用户ID无效",
                        Data = 0
                    };
                }

                var result = await _notificationService.GetUnreadNotificationCountAsync(userId);
                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取未读通知数量失败，用户ID: {UserId}", userId);
                return new ApiResult<int>
                {
                    Code = ApiEnum.Failed,
                    Msg = $"获取未读通知数量失败: {ex.Message}",
                    Data = 0
                };
            }
        }

        /// <summary>
        /// 标记通知为已读
        /// </summary>
        /// <param name="request">标记已读请求</param>
        /// <returns></returns>
        [HttpPost("mark-read")]
        public async Task<ApiResult<bool>> MarkAsRead([FromBody] MarkAsReadRequest request)
        {
            try
            {
                if (request.NotificationId <= 0 || request.UserId <= 0)
                {
                    return new ApiResult<bool>
                    {
                        Code = ApiEnum.Failed,
                        Msg = "参数无效",
                        Data = false
                    };
                }

                var result = await _notificationService.MarkAsReadAsync(request.NotificationId, request.UserId);
                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "标记通知为已读失败，通知ID: {NotificationId}, 用户ID: {UserId}", 
                    request.NotificationId, request.UserId);
                return new ApiResult<bool>
                {
                    Code = ApiEnum.Failed,
                    Msg = $"标记已读失败: {ex.Message}",
                    Data = false
                };
            }
        }

        /// <summary>
        /// 标记所有通知为已读
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <returns></returns>
        [HttpPost("mark-all-read")]
        public async Task<ApiResult<bool>> MarkAllAsRead([FromBody] MarkAllAsReadRequest request)
        {
            try
            {
                if (request.UserId <= 0)
                {
                    return new ApiResult<bool>
                    {
                        Code = ApiEnum.Failed,
                        Msg = "用户ID无效",
                        Data = false
                    };
                }

                var result = await _notificationService.MarkAllAsReadAsync(request.UserId);
                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "标记所有通知为已读失败，用户ID: {UserId}", request.UserId);
                return new ApiResult<bool>
                {
                    Code = ApiEnum.Failed,
                    Msg = $"标记所有已读失败: {ex.Message}",
                    Data = false
                };
            }
        }

        /// <summary>
        /// 删除通知
        /// </summary>
        /// <param name="request">删除通知请求</param>
        /// <returns></returns>
        [HttpDelete("delete")]
        public async Task<ApiResult<bool>> DeleteNotification([FromBody] DeleteNotificationRequest request)
        {
            try
            {
                if (request.NotificationId <= 0 || request.UserId <= 0)
                {
                    return new ApiResult<bool>
                    {
                        Code = ApiEnum.Failed,
                        Msg = "参数无效",
                        Data = false
                    };
                }

                var result = await _notificationService.DeleteNotificationAsync(request.NotificationId, request.UserId);
                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "删除通知失败，通知ID: {NotificationId}, 用户ID: {UserId}", 
                    request.NotificationId, request.UserId);
                return new ApiResult<bool>
                {
                    Code = ApiEnum.Failed,
                    Msg = $"删除通知失败: {ex.Message}",
                    Data = false
                };
            }
        }

        /// <summary>
        /// 获取通知统计信息
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <returns></returns>
        [HttpGet("statistics")]
        public async Task<ApiResult<NotificationStatisticsDto>> GetStatistics([FromQuery] int userId)
        {
            try
            {
                if (userId <= 0)
                {
                    return new ApiResult<NotificationStatisticsDto>
                    {
                        Code = ApiEnum.Failed,
                        Msg = "用户ID无效"
                    };
                }

                // 获取总通知数
                var totalResult = await _notificationService.GetUserNotificationsAsync(userId, 1, 1);
                if (totalResult.Code != ApiEnum.Success)
                {
                    return new ApiResult<NotificationStatisticsDto>
                    {
                        Code = totalResult.Code,
                        Msg = totalResult.Msg
                    };
                }

                // 获取未读通知数
                var unreadResult = await _notificationService.GetUnreadNotificationCountAsync(userId);
                if (unreadResult.Code != ApiEnum.Success)
                {
                    return new ApiResult<NotificationStatisticsDto>
                    {
                        Code = unreadResult.Code,
                        Msg = unreadResult.Msg
                    };
                }

                var statistics = new NotificationStatisticsDto
                {
                    TotalCount = totalResult.Data.TotalCount,
                    UnreadCount = unreadResult.Data,
                    ReadCount = totalResult.Data.TotalCount - unreadResult.Data,
                    TodayCount = 0, // 可以根据需要实现
                    UrgentCount = 0  // 可以根据需要实现
                };

                return new ApiResult<NotificationStatisticsDto>
                {
                    Code = ApiEnum.Success,
                    Msg = "查询成功",
                    Data = statistics
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取通知统计信息失败，用户ID: {UserId}", userId);
                return new ApiResult<NotificationStatisticsDto>
                {
                    Code = ApiEnum.Failed,
                    Msg = $"获取统计信息失败: {ex.Message}"
                };
            }
        }
    }

    #region 请求模型

    /// <summary>
    /// 标记已读请求
    /// </summary>
    public class MarkAsReadRequest
    {
        /// <summary>
        /// 通知ID
        /// </summary>
        [Required]
        public int NotificationId { get; set; }

        /// <summary>
        /// 用户ID
        /// </summary>
        [Required]
        public int UserId { get; set; }
    }

    /// <summary>
    /// 标记所有已读请求
    /// </summary>
    public class MarkAllAsReadRequest
    {
        /// <summary>
        /// 用户ID
        /// </summary>
        [Required]
        public int UserId { get; set; }
    }

    /// <summary>
    /// 删除通知请求
    /// </summary>
    public class DeleteNotificationRequest
    {
        /// <summary>
        /// 通知ID
        /// </summary>
        [Required]
        public int NotificationId { get; set; }

        /// <summary>
        /// 用户ID
        /// </summary>
        [Required]
        public int UserId { get; set; }
    }

    /// <summary>
    /// 通知统计信息
    /// </summary>
    public class NotificationStatisticsDto
    {
        /// <summary>
        /// 总通知数
        /// </summary>
        public int TotalCount { get; set; }

        /// <summary>
        /// 未读通知数
        /// </summary>
        public int UnreadCount { get; set; }

        /// <summary>
        /// 已读通知数
        /// </summary>
        public int ReadCount { get; set; }

        /// <summary>
        /// 今日通知数
        /// </summary>
        public int TodayCount { get; set; }

        /// <summary>
        /// 紧急通知数
        /// </summary>
        public int UrgentCount { get; set; }
    }

    #endregion
}








